package mx.com.crowdgine.assetloader.audio;

import java.io.File;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

public class WavAudio implements Audio{
	
	AudioFormat audioFormat;
	AudioInputStream audioInputStream;
	SourceDataLine sourceDataLine;
	File soundFile;
	static boolean stopPlayback = true;
	
	@Override
	public void load(String filename) {
		try{
			soundFile = new File(filename);
			audioInputStream = AudioSystem.getAudioInputStream(soundFile);
			audioFormat = audioInputStream.getFormat();
			
			DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class,audioFormat);
			sourceDataLine = (SourceDataLine)AudioSystem.getLine(dataLineInfo);
			
		}catch(Exception e){
			System.err.println("Could not load wav file correctly");
			e.printStackTrace();
		}
	}

	@Override
	public void play() {
		// TODO Auto-generated method stub
		if(stopPlayback){
			stopPlayback=false;
			new PlayThread().start();
		}
	}
	
	@Override
	public void stop() {
		// TODO Auto-generated method stub
		stopPlayback=true;
	}
	
	class PlayThread extends Thread{
		byte tempBuffer[] = new byte[10000];
		
		public void run(){
			try{
				audioInputStream = AudioSystem.getAudioInputStream(soundFile);
				audioFormat = audioInputStream.getFormat();
				sourceDataLine.open(audioFormat);
				sourceDataLine.start();

				int cnt;
				//Keep looping until the input read method
				// returns -1 for empty stream or the
				// user clicks the Stop button causing
				// stopPlayback to switch from false to
				// true.
				while((cnt = audioInputStream.read(
		           tempBuffer,0,tempBuffer.length)) != -1
		                       && stopPlayback == false){
			        if(cnt > 0){
			          //Write data to the internal buffer of
			          // the data line where it will be
			          // delivered to the speaker.
			          sourceDataLine.write(
			                             tempBuffer, 0, cnt);
			        }//end if
				}//end while
		      //Block and wait for internal buffer of the
		      // data line to empty.
		      sourceDataLine.drain();
		      sourceDataLine.close();
		      stopPlayback = true;
		    }catch (Exception e) {
		      e.printStackTrace();
		    }//end catch
		}//end run
	}
	
}
